/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import Beans.InventoryStoreBean;
import Beans.ItemListBean;
import Beans.MainInventoryStoreBean;
import facade.InventoryStoreFacade;
import facade.Inventory_StoreFacade;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.crypto.spec.IvParameterSpec;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import newkfp.Bill;
import newkfp.BillItem;
import newkfp.Item;
import newkfp.util.JsfUtil;
import newkfp.util.PaginationHelper;

/**
 *
 * @author A7med Kotb
 */
@ManagedBean(name = "inventoryStoreController")
@SessionScoped
public class InventoryStoreController {

    private InventoryStoreBean current;
    private DataModel items = null;
    @EJB
    private facade.InventoryStoreFacade ejbFacade;
    @EJB
    private Inventory_StoreFacade inventory_StoreFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private Date fromDate;
    private Date toDate;
    private double purchased;
    private double buyed;
    private double profit;
    private String hiddenField = "1";
    private String lastName;

    public String getHiddenField() {
        return hiddenField;
    }

    public void setHiddenField(String hiddenField) {
        this.hiddenField = hiddenField;
    }

    private InventoryStoreFacade getFacade() {
        return ejbFacade;
    }

    public double getBuyed() {
        return buyed;
    }

    public void setBuyed(double buyed) {
        this.buyed = buyed;
    }

    public double getProfit() {
        return profit;
    }

    public void setProfit(double profit) {
        this.profit = profit;
    }

    public double getPurchased() {
        return purchased;
    }

    public void setPurchased(double purchased) {
        this.purchased = purchased;
    }

    public int getSelectedItemIndex() {
        return selectedItemIndex;
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex;
    }

    public Date getFromDate() {
        return fromDate;
    }

    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    public Date getToDate() {
        return toDate;
    }

    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }

    public InventoryStoreController() {
    }

    public InventoryStoreBean getSelected() {
        if (current == null) {
            current = new InventoryStoreBean();
            selectedItemIndex = -1;
        }
        return current;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            int rows = getListOfInventoryStoreRecords().size();
            pagination = new PaginationHelper(rows) {

                @Override
                public int getItemsCount() {
                    return getListOfInventoryStoreRecords().size();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getListOfInventoryStoreRecords());
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "inventoryStore?faces-redirect=true";
    }

    public String prepareView() {
        current = (InventoryStoreBean) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View?faces-redirect=true";
    }

    public DataModel getItems() {


        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "inventoryStore?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "inventoryStore?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public String getInventory() {
        List list;
        try {
            list = getInventory_StoreFacade().getNotConfirmedBillAtPeriod(fromDate, toDate);
            if (list.size() > 0) {
                FacesContext context = FacesContext.getCurrentInstance();

                String s = "توجد بعض الفواتير لم يتم تأكيدها بعد من فضلك قم بتأكيدها أولا";
                context.addMessage(null, new FacesMessage(s));

                return "/confirmBills";
            } else {
                clearSession();
                getListOfInventoryStoreRecords();
                return prepareList();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            list = new ArrayList();
        }
    }

    public List<MainInventoryStoreBean> getListOfInventoryStoreRecords() {
        Date now = new Date();
        List<MainInventoryStoreBean> mainList = new ArrayList<MainInventoryStoreBean>();
        List<InventoryStoreBean> inventoryStoreList = new ArrayList<InventoryStoreBean>();
        HashMap items_list = getInventory_StoreFacade().getAllItems();
        HashMap hashMap = new HashMap();
        HashMap customer_items_list_super, customer_items_list_sub,
                exporter_items_list_super,
                exporter_items_list_sub;

        if (fromDate != null && toDate != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(toDate);
            c.add(Calendar.DAY_OF_MONTH, 1);
            toDate = c.getTime();
            //items from  fromdate to now super pariod for customer
            customer_items_list_super = getInventory_StoreFacade().getItemsFromBillInPariod(0, fromDate, now);
            // items from todate to now sub pariod for customer
            customer_items_list_sub = getInventory_StoreFacade().getItemsFromBillInPariod(0, toDate, now);
            //items from  fromdate to now super pariod for exporter
            exporter_items_list_super = getInventory_StoreFacade().getItemsFromBillInPariod(1, fromDate, now);
            // items from todate to now sub pariod for exporter
            exporter_items_list_sub = getInventory_StoreFacade().getItemsFromBillInPariod(1, toDate, now);
            Iterator iterator = items_list.keySet().iterator();
            //
            ItemListBean customerSuperItemListBean, customerSuperItemListBeanExecution,
                    customerSubItemListBean, customerSubItemListBeanExecution,
                    exporterSuperItemListBean, exporterSuperItemListBeanExecution, exporterSubItemListBean;
            //
            String regular = "_1";
            String productExecution = "_2";
            int i = 0;
            while (iterator.hasNext()) {
                Object object = iterator.next();
                ItemListBean itemListBean = (ItemListBean) items_list.get(object);
                if (customer_items_list_super != null && customer_items_list_super.get(object + regular) != null) {
                    customerSuperItemListBean = (ItemListBean) customer_items_list_super.get(object + regular);
                } else {
                    customerSuperItemListBean = new ItemListBean();
                }
                /////productExecution
                if (customer_items_list_super != null && customer_items_list_super.get(object + productExecution) != null) {
                    customerSuperItemListBeanExecution = (ItemListBean) customer_items_list_super.get(object + productExecution);
                    customerSuperItemListBean.setAmount(customerSuperItemListBean.getAmount() - customerSuperItemListBeanExecution.getAmount());
                    customerSuperItemListBean.setPackageCount(customerSuperItemListBean.getPackageCount() - customerSuperItemListBeanExecution.getPackageCount());
                    customerSuperItemListBean.setPrice(customerSuperItemListBean.getPrice() - customerSuperItemListBeanExecution.getPrice());
                }


                ////
                if (customer_items_list_sub != null && customer_items_list_sub.get(object + regular) != null) {
                    customerSubItemListBean = (ItemListBean) customer_items_list_sub.get(object + regular);
                } else {
                    customerSubItemListBean = new ItemListBean();
                }
                ///productExecution
                if (customer_items_list_sub != null && customer_items_list_sub.get(object + productExecution) != null) {
                    customerSubItemListBeanExecution = (ItemListBean) customer_items_list_sub.get(object + productExecution);
                    customerSubItemListBean.setAmount(customerSubItemListBean.getAmount() - customerSubItemListBeanExecution.getAmount());
                    customerSubItemListBean.setPackageCount(customerSubItemListBean.getPackageCount() - customerSubItemListBeanExecution.getPackageCount());
                    customerSubItemListBean.setPrice(customerSubItemListBean.getPrice() - customerSubItemListBeanExecution.getPrice());
                }
                ////
                if (exporter_items_list_super != null && exporter_items_list_super.get(object + regular) != null) {
                    exporterSuperItemListBean = (ItemListBean) exporter_items_list_super.get(object + regular);
                } else {
                    exporterSuperItemListBean = new ItemListBean();
                }
                //////productExecution
                if (exporter_items_list_super != null && exporter_items_list_super.get(object + productExecution) != null) {
                    exporterSuperItemListBeanExecution = (ItemListBean) exporter_items_list_super.get(object + productExecution);

                    exporterSuperItemListBean.setAmount(exporterSuperItemListBean.getAmount() - exporterSuperItemListBeanExecution.getAmount());
                    exporterSuperItemListBean.setPackageCount(exporterSuperItemListBean.getPackageCount() - exporterSuperItemListBeanExecution.getPackageCount());
                    exporterSuperItemListBean.setPrice(exporterSuperItemListBean.getPrice() - exporterSuperItemListBeanExecution.getPrice());
                }
                //////
                if (exporter_items_list_sub != null && exporter_items_list_sub.get(object + regular) != null) {
                    exporterSubItemListBean = (ItemListBean) exporter_items_list_sub.get(object + regular);
                } else {
                    exporterSubItemListBean = new ItemListBean();
                }
                //////productExecution
                if (exporter_items_list_sub != null && exporter_items_list_sub.get(object + productExecution) != null) {
                    exporterSuperItemListBeanExecution = (ItemListBean) exporter_items_list_super.get(object + productExecution);

                    exporterSubItemListBean.setAmount(exporterSubItemListBean.getAmount() - exporterSuperItemListBeanExecution.getAmount());
                    exporterSubItemListBean.setPackageCount(exporterSubItemListBean.getPackageCount() - exporterSuperItemListBeanExecution.getPackageCount());
                    exporterSubItemListBean.setPrice(exporterSubItemListBean.getPrice() - exporterSuperItemListBeanExecution.getPrice());
                }
                /////

                InventoryStoreBean inventoryStoreBean = new InventoryStoreBean();
                inventoryStoreBean.setItemName(itemListBean.getItemName());
                inventoryStoreBean.setFactoryName(itemListBean.getFactory());
                double buyedPk = customerSuperItemListBean.getPackageCount() - customerSubItemListBean.getPackageCount();
                inventoryStoreBean.setBuyedPk(buyedPk);
                double buyedQuantity = customerSuperItemListBean.getAmount() - customerSubItemListBean.getAmount();
                inventoryStoreBean.setBuyedQuantity(buyedQuantity);
                double itemPrice = customerSuperItemListBean.getPrice() - customerSubItemListBean.getPrice();
                inventoryStoreBean.setItemPrice(itemPrice);
                double pkAtFromDate = itemListBean.getPackageCount() - exporterSuperItemListBean.getPackageCount() + customerSuperItemListBean.getPackageCount();
                inventoryStoreBean.setPkAtFromDate(pkAtFromDate);
                double quantityAtFromDate = itemListBean.getAmount() - exporterSuperItemListBean.getAmount() + customerSuperItemListBean.getAmount();
                inventoryStoreBean.setQuantityAtFromDate(quantityAtFromDate);
                double remainderPk = pkAtFromDate - buyedPk;
                inventoryStoreBean.setRemainderPk(remainderPk);
                double remainderQuantity = quantityAtFromDate - buyedQuantity;
                inventoryStoreBean.setRemainderQuantity(remainderQuantity);

                if (hashMap != null) {
                    if (hashMap.get(itemListBean.getItemName()) != null) {

                        MainInventoryStoreBean mainInventoryStoreBean = (MainInventoryStoreBean) hashMap.get(itemListBean.getItemName());
//                       mainInventoryStoreBean.setItemName(itemListBean.getItemName());
                        List<InventoryStoreBean> bean = mainInventoryStoreBean.getStoreBean();
                        bean.add(inventoryStoreBean);
                        mainInventoryStoreBean.setStoreBean(bean);
                        mainInventoryStoreBean.setTotalBuyedPK(mainInventoryStoreBean.getTotalBuyedPK() + buyedPk);
                        mainInventoryStoreBean.setTotalBuyedQuantity(mainInventoryStoreBean.getTotalBuyedQuantity() + buyedQuantity);
                        if (itemPrice != 0) {

                            mainInventoryStoreBean.setTotalItemPrice(Math.abs(((mainInventoryStoreBean.getTotalItemPrice() + itemPrice) / 2) * 100) / 100);
                        }
                        mainInventoryStoreBean.setTotalPKAtFromDate(mainInventoryStoreBean.getTotalPKAtFromDate() + pkAtFromDate);
                        mainInventoryStoreBean.setTotalQuantityAtFromDate(mainInventoryStoreBean.getTotalQuantityAtFromDate() + quantityAtFromDate);
                        mainInventoryStoreBean.setTotalRemainderPK(mainInventoryStoreBean.getTotalRemainderPK() + remainderPk);
                        mainInventoryStoreBean.setTotalRemainderQuantity(mainInventoryStoreBean.getTotalRemainderQuantity() + remainderQuantity);

                        hashMap.remove(itemListBean.getItemName());
                        hashMap.put(itemListBean.getItemName(), mainInventoryStoreBean);



                    } else {
//                        i++;
//                        System.out.println(">>>>>>>>>>" + i);
                        MainInventoryStoreBean mainInventoryStoreBean = new MainInventoryStoreBean();
                        mainInventoryStoreBean.setItemName(itemListBean.getItemName());
                        inventoryStoreList = new ArrayList<InventoryStoreBean>();
                        inventoryStoreList.add(inventoryStoreBean);
                        mainInventoryStoreBean.setStoreBean(inventoryStoreList);
                        mainInventoryStoreBean.setTotalBuyedPK(buyedPk);
                        mainInventoryStoreBean.setTotalBuyedQuantity(buyedQuantity);
                        mainInventoryStoreBean.setTotalItemPrice(itemPrice);
                        mainInventoryStoreBean.setTotalPKAtFromDate(pkAtFromDate);
                        mainInventoryStoreBean.setTotalQuantityAtFromDate(quantityAtFromDate);
                        mainInventoryStoreBean.setTotalRemainderPK(remainderPk);
                        mainInventoryStoreBean.setTotalRemainderQuantity(remainderQuantity);

                        hashMap.put(itemListBean.getItemName(), mainInventoryStoreBean);
                    }
                }
            }
            Iterator it = hashMap.keySet().iterator();
            while (it.hasNext()) {
                Object object = it.next();
                MainInventoryStoreBean mainInventoryStoreBean = (MainInventoryStoreBean) hashMap.get(object);
                mainList.add(mainInventoryStoreBean);
            }
            //customer total buyed
            buyed = getInventory_StoreFacade().getTotalCash(0, fromDate, toDate);
            //exporter total purchased
            purchased = getInventory_StoreFacade().getTotalCash(1, fromDate, toDate);
            profit = buyed - purchased;
            return mainList;
        } else {
            return mainList;
        }
    }

    public void clearSession() {
        Map m = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        m.remove("exporterController");

        m.remove("employeeController");
        m.remove("customerController");
        m.remove("countryController");
        m.remove("billInformationController");
//m.remove("inventoryStoreController"); 
        m.remove("moneyController");
        m.remove("billConfirmController");
        m.remove("billExporterInformationController");
        m.remove("logController");
        m.remove("itemController");

    }

    public Inventory_StoreFacade getInventory_StoreFacade() {
        return inventory_StoreFacade;
    }

    public void setInventory_StoreFacade(Inventory_StoreFacade inventory_StoreFacade) {
        this.inventory_StoreFacade = inventory_StoreFacade;
    }
}
